<?php

namespace addons\service\controller;

use think\addons\Controller;
use addons\epay\library\Service;
use app\api\model\service\PremiumOrder;
use app\api\model\service\SkillEnsurePay;
use app\api\model\service\Skill;
use app\api\model\service\ShopEnsurePay;
use app\api\model\service\Shop;
use app\api\model\service\Order;
use addons\service\library\WxPay;
use app\api\model\service\AddOrder;
use app\api\model\service\PlusPay;
use app\common\model\User;
use Exception;
use think\Log;

class Notify extends Controller
{

    public function notifyx()
    {
        $paytype = $this->request->param('paytype');
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = Service::isVersionV3() ? $pay->callback() : $pay->verify();
        try {
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];
            $trade_no = $data['transaction_id'];
            if (strpos($out_trade_no,'remium')){
                $info = db('service_premium_order')->field('id,user_id,price')->where('orderId',$out_trade_no)->find();
                if($info['state'] == 0){
                    db('service_premium_order')->where('orderId',$out_trade_no)->update(['trade_no'=>$trade_no,'state'=>1,'paytime'=>time()]);
                    User::score(+$info['price'],$info['user_id'],'充值保证金到账');
                    Shop::where(['user_id'=>$info['user_id']])->setInc('ensure_price',$info['price']);
                    (new PremiumOrder)->finishPay($info['id']);
                }
            }elseif (strpos($out_trade_no,'oodsOrd')){
                $info = db('service_order')->where('orderId',$out_trade_no)->find();
                if($info['status'] == 0){
                    db('service_order')->where('orderId',$out_trade_no)->update(['trade_no'=>$trade_no,'status'=>1,'paytime'=>time()]);
                    Order::finishPay($info['id']);
                }
            }elseif (strpos($out_trade_no,'oodsAdd')){
                $info = db('service_add_order')->where('orderId',$out_trade_no)->find();
                if($info['state'] == 0){
                    db('service_add_order')->where('orderId',$out_trade_no)->update(['trade_no'=>$trade_no,'state'=>1,'paytime'=>time()]);
                    AddOrder::finishPay($info['id']);
                }
            }elseif (strpos($out_trade_no,'echarge')){
                $info = db('service_recharge')->where('orderId',$out_trade_no)->find();
                if($info['state'] == 0){
                    db('service_recharge')->where('orderId',$out_trade_no)->update(['trade_no'=>$trade_no,'state'=>1,'paytime'=>time()]);
                    User::money($info['price'],$info['user_id'],'充值余额到账');
                }
            }elseif(strpos($out_trade_no,'lusPay')){
                $info = db('service_plus_pay')->where('orderId',$out_trade_no)->find();
                if($info['state'] == 0){
                    db('service_plus_pay')->where('orderId',$out_trade_no)->update(['trade_no'=>$trade_no,'state'=>1,'paytime'=>time()]);
                    PlusPay::handlePlus($info['id']);
                }
            }
            //你可以在此编写订单逻辑
        } catch (Exception $e) {
        }

        //下面这句必须要执行,且在此之前不能有任何输出

        if (Service::isVersionV3()) {
            return $pay->success()->getBody()->getContents();
        } else {
            return $pay->success()->send();
        }
    }

    public function fromXml($xml)
    {
        // 禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    }


    /**
     * 支付回调
     * @return \Psr\Http\Message\ResponseInterface|string|\Symfony\Component\HttpFoundation\Response|void
     * @throws \Yansongda\Pay\Exception\ContainerException
     * @throws \Yansongda\Pay\Exception\InvalidParamsException
     * @throws \Yansongda\Pay\Exceptions\InvalidArgumentException
     * @throws \Yansongda\Pay\Exceptions\InvalidConfigException
     * @throws \Yansongda\Pay\Exceptions\InvalidSignException
     */
    public function notify()
    {
        $data = file_get_contents('php://input');
        $wxPay = new WxPay();
        $res = $wxPay->xmlToArray($data);
        $sign = $res['sign'];
        // sign不参与签名算法
        unset($res['sign']);
        // 生成签名
        $signature = $wxPay->getSign($res);
        if($sign != $signature)
        {
            echo '签名错误';
            return;
        }
        if ($res['return_code'] != 'SUCCESS') {
            echo '支付失败';
            return;
        }
        $paytype = $this->request->param('paytype');
        try {
            $payamount = $paytype == 'alipay' ? $res['total_amount'] : $res['total_fee'] / 100;
            $out_trade_no = $res['out_trade_no'];
            $trade_no = $res['transaction_id'];
            if (strpos($out_trade_no,'killEn')){
                $info = db('service_skill_ensure_pay')->field('id,user_id,price,state')->where('orderId',$out_trade_no)->find();
                if($info['state'] == 0){
                    db('service_skill_ensure_pay')->where('orderId',$out_trade_no)->update(['trade_no'=>$trade_no,'state'=>1,'paytime'=>time()]);
                    Skill::where(['user_id'=>$info['user_id']])->setInc('ensure_price',$info['price']);
                    (new SkillEnsurePay)->updateSkillEnsure($info['user_id'],$info['price']);
                }
            }elseif (strpos($out_trade_no,'hopEn')){
                $info = db('service_shop_ensure_pay')->field('id,user_id,price,state')->where('orderId',$out_trade_no)->find();
                if($info['state'] == 0){
                    db('service_shop_ensure_pay')->where('orderId',$out_trade_no)->update(['trade_no'=>$trade_no,'state'=>1,'paytime'=>time()]);
                    Shop::where(['user_id'=>$info['user_id']])->setInc('ensure_price',$info['price']);
                    (new ShopEnsurePay)->updateShopEnsure($info['user_id'],$info['price']);
                }
            }
        } catch (Exception $e) {
        }
        return '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';


    }

    /**
     * 支付返回，仅供开发测试
     */
    public function returnx()
    {
        $paytype = $this->request->param('paytype');
        $out_trade_no = $this->request->param('out_trade_no');
        $pay = Service::checkReturn($paytype);
        if (!$pay) {
            $this->error('签名错误', '');
        }

        //你可以在这里通过out_trade_no去验证订单状态
        //但是不可以在此编写订单逻辑！！！

        $this->success("请返回网站查看支付结果", addon_url("epay/index/index"));
    }
}
